var customerProduct = {
    params: {
        providerId: '',//服务商ID
        spuName: '',//商品名称
        channelId: "",//渠道id
        skuCode: "",//sku编码
        spuCode: '',// spu编码
        salesStatus: "",//审核状态  10:待上架 20:已上架 30:已下架
        pageNum: 1,
        pageSize: 20,
    },
    //初始化数据
    init: function () {
        this.addClick();
        this.getData();
        this.getCooperationByProviderInfo();
    },
    // 事件处理
    addClick: function () {
        // 新增
        $('#addBtn').on('click', function () {
            var url = layer.open({
                type: 2,
                title: '新增',
                content: 'customerUpdate.html?params=' + 'add'
            });
            layer.full(url);
        });
        // 服务商模糊搜索
        $('#providerId').on('keyup', function () {
            $('.search').show();
            customerProduct.findAllInfo($('#providerId').val())
        });
        // 选择服务商查询结果
        $('.search').delegate('.search-item', 'click', function () {
            var itemId = $(this).attr('data-id');
            var itemName = $(this).text();
            $('.service-productName').val(itemName);
            $('.search').hide();
            customerProduct.params.providerId = itemId;
        });
        $(document).on('click', function () {
            $('.search').hide();
        })
        // 查询
        $('#searchBtn').on('click', function () {
            var spuName = $('#spuName').val(); //商品名称
            var spuCode = $('#spuCode').val(); //SPU码
            var skuCode = $('#codeNum').val(); //Code码
            var belongChannel = $('#belongChannel').find('option:selected').val();
            var status = $('#status').find('option:selected').val();
            customerProduct.params.spuName = spuName;
            customerProduct.params.pageNum = 1;
            customerProduct.params.pageSize = 20;
            customerProduct.params.spuCode = spuCode;
            customerProduct.params.skuCode = skuCode;
            customerProduct.params.salesStatus = status;
            customerProduct.params.channelId = belongChannel;
            customerProduct.getData();

        });
        // 重置
        $('#resetBtn').on('click', function () {
            customerProduct.params.providerId = '';
            customerProduct.params.spuName = '';
            customerProduct.params.channelId = '';
            customerProduct.params.skuCode = '';
            customerProduct.params.spuCode = '';
            customerProduct.params.salesStatus = '';
            customerProduct.params.pageNum = 1;
            customerProduct.params.pageSize = 20;
        });
        // 导出
        $('#importBtn').unbind().on('click', function () {
            customerProduct.download();
        })
    },
    // 下载文件
    download: function () {
        var providerId = customerProduct.params.providerId;
        var spuName = $('#spuName').val();
        var belongChannel = $('#belongChannel').find('option:selected').val();
        var skuCode = $('#codeNum').val();
        var spuCode =  $('#spuCode').val();
        var salesStatus = $('#status').find('option:selected').val();
        var url = root.serviceProviderManagement.customerProductListExport
            + '?providerId=' + providerId + '&spuName=' + spuName + '&channelId=' + belongChannel + '&skuCode=' + skuCode + '&spuCode=' + spuCode + '&salesStatus=' + salesStatus;

        $.fileDownload(url, {
            httpMethod: 'get',
            prepareCallback: function (url) {
                console.log('下载中')
            },
            successCallback:function(url){
                console.log('导出')
            },
            failCallback: function (html, url) {
                customerProduct.downLoadErrorInfo();
            }
        })
    },
    // 导出错误信息提示--为了获取导出的错误信息因为不知道错误信息的具体原因（有的是网络出错，有的原因可能是条数的限制）
    downLoadErrorInfo:function(){
        var params = {
            providerId:customerProduct.params.providerId,
            spuName:$('#spuName').val(),
            channelId:$('#belongChannel').find('option:selected').val(),
            skuCode:$('#codeNum').val(),
            spuCode:$('#spuCode').val(),
            salesStatus:$('#status').find('option:selected').val()
        }
        $.ajax({
            type: "GET",
            url:root.serviceProviderManagement.customerProductListExport,
            contentType:'application/json;charset=utf-8', //设置请求头信息
            responseType: 'blob',
            data:params,
            dataType: "json",
            success:function(data){
                if(data.errorCode !== 0){
                    layer.msg(data.msg,{'offset':'t'})
                }
            },
            error:function(data){

            }
        })
    },
    // 获取服务商数据
    findAllInfo: function (name) {
        var params = {
            status: '',
            name: name
        }
        var successData = function (data) {
            if (data.code == 0) {
                if (data.data && data.data.length > 0) {
                    var result = data.data;
                    var str = ''
                    result.forEach(function (item) {
                        str += '<li class="search-item" data-id="' + item.id + '">' + item.name + '</li>'
                    });
                    $('.search').html(str)
                } else {
                    var emptyStr = '<li class="search-item">暂无数据</li>';
                    $('.search').html(emptyStr)
                }
            }
        }
        return web.doAjax(root.serviceProviderManagement.findAll, 'post', params, successData, 2);
    },
    // 获取专属渠道
    getCooperationByProviderInfo: function () {
        var params = {
            providerId: ''
        }
        var successData = function (data) {
            if (data.code == 0) {
                if (data.data.length > 0) {
                    var result = data.data;
                    var str = '';
                    result.forEach(function (item) {
                        str += '<option value="' + item.channelId + '">' + item.channelName + '</option>'
                    });
                    var newStr = ' <option value="">请选择专属渠道</option>' + str;
                    $('#belongChannel').html(newStr)
                } else {
                    var emptyStr = '<option value="">暂无数据</option>';
                    $('#belongChannel').html(emptyStr)
                }
            }
        }
        return web.doAjax(root.serviceProviderManagement.findProviderCooperationByProviderId, 'post', params, successData, 2);
    },
    // 获取列表数据
    getData: function () {
        var successData = function (data) {
            if (data.errorCode == 0) {
                if (!!data.data && data.data.data.length > 0) {
                    customerProduct.renderListsData(data.data.data)
                    $(".M-box3").pagination({
                        pageCount: data.data.pageCount,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            customerProduct.params.pageNum = api.getCurrent()
                            var successData = function (data) {
                                customerProduct.renderListsData(data.data.data)
                            }
                            return web.doAjax(root.serviceProviderManagement.customerProductListPage, 'post', customerProduct.params, successData, 1)
                        }
                    })
                } else {
                    $(".M-box3").pagination({
                        pageCount: 0
                    })
                    customerProduct.renderListsData(data.data.data)
                }
            } else {
                layer.msg('数据异常')
            }

        }
        return web.doAjax(root.serviceProviderManagement.customerProductListPage, 'post', customerProduct.params, successData, 1);
    },
    // 渲染列表数据
    renderListsData: function (data) {
        var ary = [];
        var obj = {};
        if (data.length > 0) {
            data.forEach(function (item) {
                if (!obj[item.spuId]) {
                    ary.push({
                        spuId: item.spuId,
                        providerName: item.providerName,
                        spuCode: item.spuCode ? item.spuCode : null,
                        skuCode: item.skuCode ? item.skuCode : null,
                        isExistWaitAuditSku: item.isExistWaitAuditSku,
                        result: [item]
                    });
                    obj[item.spuId] = item
                } else {
                    ary.forEach(function (item2) {
                        if (item2.spuId == item.spuId) {
                            item2.result.push(item)
                        }
                    })
                }
            })
            customerProduct.tableLists(ary)
        } else {
            var emptyStr = '<div style="background: #ffff;text-align: center;font-size: 14px;padding-top: 10px;">暂无商品</div>';
            $('#table-lists').html(emptyStr)
        }

    },
    // 表格数据拼接
    tableLists: function (data) {
        var tableLists = $('#table-lists');
        var tableDataStr = '';
        data.forEach(function (item) {

            var providerName = item.providerName ? item.providerName : '';//服务商名称
            var spuCode = item.spuCode ? item.spuCode : '';//spu码
            var tableData = item.result;// 表格里面的数据
            var multipleExamine = ''
            var titleStr = '';
            var newStr = '';
            var itemTable = '';
            titleStr = ' <div class="title">' +
                '                   <div class="title-left">' +
                '                       <span>服务商名称：</span>' +
                '                       <span>' + providerName + '</span>' +
                '                       <span class="spuCode">SPU码：' + spuCode + '</span>' +
                '                   </div>' +
                '                    <div class="title-right" onclick="customerProduct.updateDetail(\'' + item.spuId + '\',\'' + item.skuCode + '\',' + item.isExistWaitAuditSku + ')">修改</div>' +
                '                </div>'
            tableData.forEach(function (item) {
                var status = '';
                var operateStr = '';// 操作的按钮的字符串
                if (item.salesStatus == 10) {
                    status = '待上架'
                } else if (item.salesStatus == 20) {
                    status = '已上架'
                } else if (item.salesStatus == 30) {
                    status = '已下架'
                } else {
                    status = '';
                }

                var imgUrl = item.spuImages.length > 0 ? item.spuImages[0].attachmentUrl : '';
                var channelPrice = item.channelPrice ? item.channelPrice.toFixed(2) : 0.00;
                var unitName = item.unitName ? '/' + item.unitName : '';
                var xfsPurchasePrice = item.xfsPurchasePrice ? item.xfsPurchasePrice.toFixed(2) : 0.00;
                operateStr = '<td width="80">' +
                    '                  <div class="operate-btn" style="margin-bottom: 10px" onclick="customerProduct.queryDetail(' + item.spuId + ')">查看详情</div>' +
                    '         </td>'

                itemTable +=
                    '<tr>' +
                    '           <td width="190" class="text-l" style="padding-left: 20px">' +
                    '              <img src="' + imgUrl + '" alt="" class="table-img">' +
                    '                   <div class="img-title">' +
                  /*  '                         <p>'+item.spuName+'</p>' +
                    '                          <p>'+item.specifications+'</p>' +*/
                    '                           <p>'+item.skuName+'</p>'+
                    '                    </div>' +
                    '              </td>' +
                    '              <td width="100">' + item.skuCode + '</td>' +
                    '              <td width="80">' + item.channelName + '</td>' +
                    '              <td width="80">￥' + channelPrice + unitName +'</td>' +
                    '              <td width="100">￥' + xfsPurchasePrice + unitName +'</td>' +
                    '              <td width="100">' + item.updateTime + '</td>' +
                    '              <td width="80" style="color:#0a60d6;cursor: pointer;" onclick="customerProduct.updateStatus(\'' + item.skuId + '\',\'' + item.salesStatus + '\',\'' + item.skuCode + '\')">' + status + '</td>' + operateStr
                '</tr>';
            });
            newStr += titleStr + '<table class="table table-border table-bg table-hover table-sort">' + itemTable + '</table>';
            tableDataStr += newStr;
        })
        tableLists.html(tableDataStr)
    },
    // 查看详情
    queryDetail: function (spuId) {
        var url = layer.open({
            type: 2,
            title: '查看详情',
            content: 'customerQueryDetail.html?spuId=' + spuId
        });
        layer.full(url);
    },
    // 修改
    updateDetail: function (spuId, skuCode, isExistWaitAuditSku) {
        if (isExistWaitAuditSku) {
            layer.msg('商品已处于审核中,无法修改!')
            return false;
        }
        if (!skuCode) {
            layer.msg('商品信息同步，请稍后再试!')
            return false;
        }

        var url = layer.open({
            type: 2,
            title: '修改',
            content: 'customerUpdate.html?spuId=' + spuId
        });
        layer.full(url);
    },
    // 点击更新状态
    updateStatus: function (skuId, status, skuCode) {
        if (!skuCode) {
            layer.msg('不可操作该商品')
            return false
        }
        if (status == 30) {
            var curIndex = layer.confirm('是否确认上架该商品', {
                title: '上/下架',
            }, function () {
                customerProduct.salePutByAdminInfo(skuId)
                layer.close(curIndex);
            }, function () {
                layer.close(curIndex);
            })
        } else if (status == 20) {
            var curIndex1 = layer.confirm('是否确认下架该商品', {
                title: '上/下架',
            }, function () {
                customerProduct.saleOffByAdminInfo(skuId)
                layer.close(curIndex1);
            }, function () {
                layer.close(curIndex1);
            })
        } else {
            layer.msg('不可操作该商品')
        }

    },
    // 上架
    salePutByAdminInfo: function (skuIds) {
        var params = {
            skuIds: [skuIds],
            updateUserId: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            updateUserName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }
        var successData = function (result) {
            if (result.errorCode == 0) {
                var operateErrorSkus = result.data.operateErrorSkus;
                if(operateErrorSkus && operateErrorSkus.length > 0 ){
                    layer.msg(operateErrorSkus[0].message);
                }else{
                    layer.msg('上架成功');
                    customerProduct.getData()
                }
            } else {
                layer.msg(result.msg,{offset:'t'})
            }
        }
        return web.doAjax(root.serviceProviderManagement.salePutByAdmin, 'post', params, successData, 1);
    },
    // 下架
    saleOffByAdminInfo: function (skuIds) {
        var params = {
            skuIds: [skuIds],
            updateUserId: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            updateUserName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }
        var successData = function (result) {
            if (result.errorCode == 0) {
                layer.msg('下架成功')
                customerProduct.getData()
            } else {
                layer.msg(result.msg)
            }
        }
        return web.doAjax(root.serviceProviderManagement.saleOffByAdmin, 'post', params, successData, 1);
    }


}
customerProduct.init();